package com.dbpediamobile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.w3c.dom.Document;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;

import android.R.color;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Spannable;
import android.text.style.BackgroundColorSpan;
import android.text.style.StyleSpan;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ArticuloSimple extends Activity{

	private BusquedaSimple busqueda;
	private int indice=0;//indice para buscar palabras
	private InputStream articuloRDF;
	Articulo a = null;
	ArticuloConexion ac ;
	EditText et;
	String input;
	public Context cont;
	private ProgressDialog progressD = null; 
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		cont = this;
		progressD = ProgressDialog.show(ArticuloSimple.this, "Please wait...", "Loading...", true);
        new Thread(new Runnable(){
            public void run(){      	
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
            	handler.sendEmptyMessage(1);
	        }
        }).start();
		
	}
	public Object fetch(String address) throws MalformedURLException,IOException {
		URL url = new URL(address);
		Object content = url.getContent();
		return content;
	}
	
	
	 Handler handler = new Handler(){
			public void handleMessage(Message msg) {
				setContentView(R.layout.article); 
				//se buscan vistas del articulo
				ImageView iv = (ImageView)findViewById(R.id.logo_article);
				TextView titulo = (TextView)findViewById(R.id.title_article);
				TextView resumen = (TextView)findViewById(R.id.bodycontent);
				TextView page = (TextView)findViewById(R.id.page_content);
				TextView homepage = (TextView)findViewById(R.id.homepage_content);
				TextView subjects = (TextView)findViewById(R.id.subject_content);
				//inicializa variables
				
				busqueda = new BusquedaSimple();
				input = busqueda.input;
				
				//con la clase articulo conexion se parsean los datos
				ac = new ArticuloConexion();
				
				try {
					a = ac.getArticulo(input);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} 
				//se setea link de pagina wiki
				page.setText(a.page, TextView.BufferType.SPANNABLE);
				//se setea subjects
				subjects.setText(a.subject, TextView.BufferType.SPANNABLE);
				//se setea link del homepage
				homepage.setText(a.homepage, TextView.BufferType.SPANNABLE);
				//se obtiene imagen
				String link = a.image;
				//se definen los textos como spannables, lo que quiere decir que
				//podemos darle formato a su texto
				titulo.setText(a.label_en, TextView.BufferType.SPANNABLE);
				resumen.setText(a.resumen_en, TextView.BufferType.SPANNABLE);
				//se intenta descargar la imagen asociada (si es que existe)
				InputStream is;
				try {
					is = (InputStream)fetch(link);
					Drawable d = Drawable.createFromStream(is, "src");
					
					iv.setImageDrawable(d);
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// ejemplos de formateo de texto (antes debe setearse como spannable)
				//str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				//str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				//str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				
	            	
		         progressD.dismiss();
		   }
		};
	
	
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	//agrega los menus directamente desde main_menu.xml
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.articulo_menu, menu);
        return true;
    }

    /* Handles item selections */
    public boolean onOptionsItemSelected(MenuItem item) {
    	Intent intent;
        switch (item.getItemId()) {
        case R.id.articulo_goBackMapa:         
        	intent = new Intent(ArticuloSimple.this, DBPediaMobile.class);
        	startActivity(intent); 
        	break; 
       /* case R.id.menu_bookmarks:		        	
        	intent = new Intent(ArticuloSimple.this, ArticuloBookmarks.class);
	        startActivity(intent); 
        	break;	*/
        	/*
        case R.id.menu_guardar_art:		        	
        	if(artbd.insertArticulo(a)!=-1){
        		//informa que no hubo errores al insertar
        		Toast.makeText(getBaseContext(),"Article bookmarked successfully!", Toast.LENGTH_LONG).show();
        	}
        	else{
        		//error found
        		Toast.makeText(getBaseContext(),"Error bookmarking", Toast.LENGTH_LONG).show();
        	}
        	break;	
        	*/
        case R.id.buscar_en_articulo:
        	LinearLayout ll = (LinearLayout) this.findViewById(R.id.busqueda_articulo_layout);
        	//new ViewGroup.LayoutParams(width, height)
        	TextView tv = new TextView(this.getApplicationContext());
        	ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 
        	tv.setText(R.string.search);
        	tv.setText(tv.getText().toString()+": ");
        	et = new EditText(getApplicationContext());
        	params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); 
        	et.setLayoutParams(params);
        	//agregamos listeners
    		et.setOnKeyListener(textInputListener);
    		et.setSingleLine(true);
        	ll.addView(tv);
        	ll.addView(et);
        	
        	break;
        case R.id.respaldar_articulo:
        	this.articuloRDF = ac.getRDF();
        	File path = new File("/data/data/com.dbpediamobile/files");
            File file = new File(path, input+".rdf");
            try {
                // Make sure the Download directory exists.
                path.mkdirs();

                // Very simple code to copy a picture from the application's
                // resource into the external file.  Note that this code does
                // no error checking, and assumes the picture is small (does not
                // try to copy it in chunks).  Note that if external storage is
                // not currently mounted this will silently fail.
                InputStream is = articuloRDF;
                OutputStream os = new FileOutputStream(file);
                byte[] data = new byte[articuloRDF.available()];
                is.read(data);
                os.write(data);
                is.close();
                os.close();

                // Tell the media scanner about the new file so that it is
                // immediately available to the user.
                MediaScannerConnection.scanFile(this,
                        new String[] { file.toString() }, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
					public void onScanCompleted(String arg0, Uri arg1) {
						// TODO Auto-generated method stub
						
					}
                });
                Toast.makeText(getBaseContext(),"File "+input+".rdf"+" saved successfully in: "+path, Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                // Unable to create file, likely because external storage is
                // not currently mounted.
            	Toast.makeText(getBaseContext(),"Error saving file: "+e.getMessage(), Toast.LENGTH_LONG).show();	
            }
        	break;
       
        }
        return false;
    }
  //oyente para el textInput
    private OnKeyListener textInputListener= new OnKeyListener() {
		public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
			// arg1:codigo de la tecla
			if(arg2.getAction()==1){//key release
				if(arg1==66){//66 corresponde a Enter
					buscar();
				}
			}
			return false;
		}
    };
    //busca en el articulo el input especificado
    private void buscar(){
    	EditText editTextInput = et;
    	String input = editTextInput.getText().toString();
    	int largoInput = input.length();
    	
    	TextView resumen = (TextView) this.findViewById(R.id.bodycontent);
    	String textoResumen = resumen.getText().toString();
    	//busca dentro del resumen el texto del input
    	resumen.setText(textoResumen, TextView.BufferType.SPANNABLE);
    	for(int i=0 ;i<textoResumen.length()-largoInput;i++){
    		if(textoResumen.substring(i, i+largoInput).compareTo(input)==0){
    			Spannable str = (Spannable) resumen.getText();
    			str.setSpan(new BackgroundColorSpan(0xFFFFFF00), i, i+largoInput, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    		}
    	}
    	
    }
}
